import { getUserRouter, login } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, getUserInfo, getUserRoutes, removeToken, removeUserInfo, removeUserRoutes, setToken, setUserINfo, setUserRoutes } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: getUserInfo(),
    userRoutes: getUserRoutes(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token, expires) => {
    state.token = token
    setToken(token, expires)
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    setUserINfo(userInfo)
  },
  SET_USER_ROUTES: (state, routes) => {
    state.userRoutes = routes
    setUserRoutes(routes)
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { token, user } = await login({ ...userInfo })
    commit('SET_TOKEN', token.token, token.expire / (24 * 60 * 60))
    commit('SET_USER_INFO', user)
  },

  async getUserRoutes({ commit }) {
    const res = await getUserRouter()
    commit('SET_USER_ROUTES', res)
  },

  // user logout
  logout({ commit }) {
    removeToken() // must remove  token  first
    removeUserInfo()
    removeUserRoutes()
    resetRouter()
    commit('RESET_STATE')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

